<?php

namespace App\Listeners;

use App\Models\Map\Mch;
use App\Models\Map\ShopOrder;
use App\Models\Order\FailEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Http;

class CommissionListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        $order = $event->order;

        if($order&&$order->real_price>0){
            $area_code = Mch::query()->where('id',$order->mch_id)->value('area_code');
            $data = [
                'totalAmount'=>$order->real_price,
                'productId'=>[
                    [
                        'goods_id'=>'1112'.$order->goods_id,
                        'goods_num'=>$order->quantity,
                        'price'=>$order->real_price*$order->commission_rate,
                        'goods_price'=>$order->real_price,
                        'create_time'=>time(),
                        'order_id'=>$order->out_trade_no,
                        'area'=> $area_code,
                        'share'=> $order->temp_openid??'',
                    ]
                ],
                'orderId'=>$order->out_trade_no,
                'paymentMethod'=>4,
                'userId'=>$order->openid
            ];
//            info('传递数据为',$data);
            $response = Http::post(env('COMMISSION_URL').'/pay_divide/createOrders/', $data);
            $last = $response->body();
//            info('分佣接口返回数据'.$last);
            if($last){
                // 事件错误日志
                $result = json_decode($last,true);
                if($result['code'] !== 20000){
                    $err['id'] = $order->id;
                    $err['order'] = $order;
                    $err['order_table'] = $event->order_table??'shop_orders';
                    $err['error'] = $last;
                    FailEvent::query()->create($err);
                }
            }
        }
    }
}
